package cn.tedu.ivos.application.service.impl;

import cn.tedu.ivos.application.mapper.ApplicationMapper;
import cn.tedu.ivos.application.pojo.dto.ApplicationQuery;
import cn.tedu.ivos.application.pojo.dto.ApplicationSaveParam;
import cn.tedu.ivos.application.pojo.entity.Application;
import cn.tedu.ivos.application.pojo.vo.ApplicationVO;
import cn.tedu.ivos.application.service.ApplicationService;
import cn.tedu.ivos.audit.pojo.vo.AuditVO;
import cn.tedu.ivos.audit.service.AuditService;
import cn.tedu.ivos.base.enums.ApplicationStatusEnum;
import cn.tedu.ivos.user.mapper.UserMapper;
import cn.tedu.ivos.user.pojo.dto.UserQuery;
import cn.tedu.ivos.user.pojo.vo.UserVO;
import cn.tedu.ivos.user.service.UserService;
import cn.tedu.ivos.vehicle.mapper.VehicleMapper;
import cn.tedu.ivos.vehicle.pojo.entity.Vehicle;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringJoiner;

/* @Transactional是Spring提供的一个用于管理事务的注解
* 主要是用于管理对数据库做操作时,可以确保方法中的所有数据库操作都在同一个事务中执行,要么都成功,要么都失败*/
@Transactional
@Slf4j
@Service
public class ApplicationServiceImpl implements ApplicationService {
    @Autowired
    private ApplicationMapper applicationMapper;
    @Autowired
    private AuditService auditService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private VehicleMapper vehicleMapper;

    @Override
    public void saveApplication(ApplicationSaveParam applicationSaveParam) {
        log.debug("保存用车申请:applicationSaveParam={}",applicationSaveParam);
        Application application = new Application();
        BeanUtils.copyProperties(applicationSaveParam,application);
        application.setCreateTime(new Date());
        application.setStatus(ApplicationStatusEnum.PENDING.getCode());
        /*遇到的问题:新增申请单对应的审批单数据时,审批单数据没有此申请单id*/
        //原因:执行insert方法的SQL时,没有把生成的自增主键值回填到application对象中
        //解决方法:给此SQL添加 useGeneratedKeys="true" keyProperty="id"
        //效果:JDBC会为当前application对象自动生成自增主键,比并将生成的主键赋值给当前application对象的id属性
        applicationMapper.insert(application);
        //在上方创建好申请单后,调用审批模块的方法
        //为此申请单创建对应的审批单数据
        auditService.insertAudit(application);
    }

    @Override
    public List<ApplicationVO> selectApplication(ApplicationQuery applicationQuery) {
        log.debug("查询用车申请:applicationQuery={}",applicationQuery);
        List<ApplicationVO> list= applicationMapper.selectApplication(applicationQuery);
        /*for(ApplicationVO applicationVO:list){
            Long userId = applicationVO.getUserId();
            UserQuery userQuery = new UserQuery();
            userQuery.setId(userId);
            List<UserVO> userList = userService.selectUser(userQuery);
            Long parentId = userList.get(0).getParentId();
            List<UserVO> auditUserList = userService.selectAuditUser(parentId);
            String auditUsernameList;
            if(auditUserList.size()>1){
                auditUsernameList = auditUserList.get(0).getUsername() + "," + auditUserList.get(1).getUsername();
            }else{
                auditUsernameList = auditUserList.get(0).getUsername();
            }
            applicationVO.setAuditUsernameList(auditUsernameList);
        }*/
        //依次取出每一个申请单VO,为它补全对应的审批人数据
        for(int i=0; i<list.size(); i++){
            ApplicationVO applicationVO = list.get(i);
            //处理当前的申请单VO,给它补全审批人字段的值
            assignAuditUserList(applicationVO);
        }
        return list;
    }

    /* 本方法用于给当前传入的申请单VO的审批人数据赋值,并不会生成新的申请单VO
    * 审批人id集合 List<Long> auditUserIdList => [106,103]
    * 审批人姓名字符串String auditUsernameList => "moly,tom"
    * */
    private void assignAuditUserList(ApplicationVO applicationVO){
        //1.准备空集合,分别用来保存此申请单对应的审批人id集合和姓名字符串
        List<Long> auditUserIdList = new ArrayList<>();
        List<String> auditUsernameList = new ArrayList<>();
        //2.根据传入的申请单对象,获取id,再差出所有的审批单
        List<AuditVO> auditVOList =
                auditService.selectAuditByApplicationId(applicationVO.getId());
        /*//3.依次遍历取出每一个审批单对象
        for(AuditVO auditVO:auditVOList){
            //4.获取当前遍历到的审批单中的审批人数据
            auditUserIdList.add(auditVO.getAuditUserId());
            Long id = auditVO.getAuditUserId();
            //5.根据刚刚取出来的审批人id查出此人姓名,并装入上方审批人姓名空集合中
            UserVO userVO = userService.selectById(id);
            auditUsernameList.add(userVO.getUsername());
        }*/
        //3.依次遍历取出每一个审批单对象
        for (int i = 0; i < auditVOList.size(); i++) {
            AuditVO auditVO = auditVOList.get(i);
            //4.获取当前遍历到的审批单中的审批人数据
            Long id = auditVO.getAuditUserId();
            auditUserIdList.add(id);
            //5.根据刚刚取出来的审批人id查出此人姓名,并装入上方审批人姓名空集合中
            UserVO userVO = userMapper.selectById(id);
            auditUsernameList.add(userVO.getUsername());
        }
        //6.准备一个拼接工具,帮我们将多个审批人姓名连成一个字符串
        StringJoiner sj = new StringJoiner(",");
        for(String username:auditUsernameList){
            sj.add(username);
        }
        //7.将拼接好的审批人姓名字符串赋值给方法形参ApplicationVO
        applicationVO.setAuditUserIdList(auditUserIdList);
        //8.将准备好的审批人id集合赋值给方法形参ApplicationVO
        applicationVO.setAuditUsernameList(sj.toString());
        /*Long userId = applicationVO.getUserId();
        UserQuery userQuery = new UserQuery();
        userQuery.setId(userId);
        List<UserVO> userList = userService.selectUser(userQuery);
        Long parentId = userList.get(0).getParentId();
        List<UserVO> auditUserList = userService.selectAuditUser(parentId);
        String auditUsernameList;
        if(auditUserList.size()>1){
            auditUsernameList = auditUserList.get(0).getUsername() + "," + auditUserList.get(1).getUsername();
        }else{
            auditUsernameList = auditUserList.get(0).getUsername();
        }
        List<Long> auditUserIdList = new ArrayList<>();
        for(UserVO userVO:auditUserList){
            auditUserIdList.add(userVO.getId());
        }
        applicationVO.setAuditUserIdList(auditUserIdList);
        applicationVO.setAuditUsernameList(auditUsernameList);*/
    }

    @Override
    public void cancelApplication(Long id) {
        log.debug("取消申请业务:id={}",id);
        Application application = new Application();
        application.setStatus(ApplicationStatusEnum.CANCEL.getCode());
        application.setId(id);
        application.setUpdateTime(new Date());
        applicationMapper.update(application);
        /*List<AuditVO> list = auditService.selectAuditByApplicationId(id);
        for(AuditVO auditVO:list){
            Long auditId = auditVO.getId();
            auditService.deleteAudit(auditId);
        }*/
        auditService.deleteByApplicationId(id);
    }

    @Override
    public void distribute(Long id, Long vehicleId) {
        log.debug("分配车辆业务:id={},vehicleId={}",id,vehicleId);
        Application application = new Application();
        application.setId(id);
        application.setStatus(ApplicationStatusEnum.ALLOCATION.getCode());
        application.setVehicleId(vehicleId);
        application.setUpdateTime(new Date());
        applicationMapper.update(application);
        Vehicle vehicle = new Vehicle();
        vehicle.setId(vehicleId);
        vehicle.setStatus("2");
        vehicle.setUpdateTime(new Date());
        vehicleMapper.update(vehicle);
    }

    @Override
    public void back(Long applicationId, Long vehicleId) {
        log.debug("归还车辆业务:applicationId={},vehicleId={}",applicationId,vehicleId);
        Application application = new Application();
        application.setId(applicationId);
        application.setStatus(ApplicationStatusEnum.END.getCode());
        application.setUpdateTime(new Date());
        applicationMapper.update(application);

        //还车需要把车辆状态改为空闲
        Vehicle vehicle = new Vehicle();
        vehicle.setId(vehicleId);
        vehicle.setStatus("1");
        vehicle.setUpdateTime(new Date());
        vehicleMapper.update(vehicle);
    }
}
